<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/11/15
 * Time: 9:20
 */

namespace app\common\library\ali\rabittmq;


use app\admin\model\order\Order;
use PhpAmqpLib\Connection\AMQPStreamConnection;

class Consumer
{
    protected $connection;

    protected $queue;

    protected $channel;

    protected $message;

    public function __construct()
    {
        if (config('aliAmqp.type') == 'ali') {
            $user = (new AliConfig())->getUser();
            $password = (new AliConfig())->getPassword();

        } else {
            $user = config('aliAmqp.user');
            $password = config('aliAmqp.password');
        }
        $host = config('aliAmqp.host');
        $port = config('aliAmqp.port');
        $vhost = config('aliAmqp.vhost');
        $this->connection = new AMQPStreamConnection($host, $port, $user, $password,$vhost);
        $this->channel = $this->connection->channel();

    }

    public function setQueue($queue)
    {
        $this->queue = $queue;
        $this->channel->queue_declare($queue, false, true, false, false);
    }

    public function run(){
        echo "start : ····";
        $callback = function ($msg){
            $msg_data = json_decode($msg->body,true);
            var_dump($msg_data);
            $order_id = $msg_data['order_id'];
            $order = new Order();
            $order->sendSms($order_id);
        };

        $this->channel->basic_consume($this->queue, '', false, true, false, false, $callback);

        while ($this->channel->is_consuming()) {
            $this->channel->wait();
        }

        $this->channel->close();
        $this->connection->close();

    }

}